import { computed } from 'vue'

function useShortcut(props, scrollRef, listWrapper) {
  const shortcutList = computed(() => {
    return props.data.map(item => item.title)
  })

  const moveInfo = {}
  const DOM_HEIGHT = 18

  function onTouchstart(e) {
    moveInfo.pageY = e.touches[0].pageY
    const index = parseInt(e.target.dataset.index)
    moveInfo.startIndex = index
    scrollTo(index)
  }

  function onTouchmove(e) {
    const d = e.touches[0].pageY - moveInfo.pageY
    const nowIndex = moveInfo.startIndex + Math.floor(d / DOM_HEIGHT)
    scrollTo(nowIndex)
  }

  function scrollTo(index) {
    if (isNaN(index)) return
    index = Math.max(0, Math.min(index, shortcutList.value.length - 1))
    const targetEle = listWrapper.value.children[index]
    const scroll = scrollRef.value.scroll
    scroll.scrollToElement(targetEle, 0)
  }

  return { shortcutList, onTouchstart, onTouchmove }
}

export default useShortcut
